package com.example.freeengine.wallpaper.fragment.everydayrefresh.picturesource;

import android.content.Context;
import android.os.Looper;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.freeengine.wallpaper.MyThreadPool;
import com.example.freeengine.wallpaper.network.MyVolleyRequestQueueSingleton;
import com.example.freeengine.wallpaper.network.VolleyCallback;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Terry Deng
 */
public class BingPictureSource {

    private static final String TAG = BingPictureSource.class.getSimpleName();

    static String host1 = "https://cn.bing.com/HPImageArchive.aspx?format=js&idx=1&n=1&pid=hp&uhd=1&uhdwidth=720&uhdheight=1280";
    static String host2 = "https://cn.bing.com";
    // https://cn.bing.com/th?id=OHR.TanzaniaBeeEater_ZH-CN3246625733_UHD.jpg&rf=LaDigue_UHD.jpg&pid=hp&w=720&h=1280&rs=1&c=4

    public static void generatePictureUrl(Context context, VolleyCallback callback){
        StringRequest request = new StringRequest(Request.Method.GET, host1, response -> {
            Log.i(TAG, "generatePictureUrl: ");
            try {
                BingData bingData = new ObjectMapper().readValue(response, BingData.class);
                if (bingData != null && bingData.getImages() != null
                        && !bingData.getImages().isEmpty()) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            callback.onSuccess(host2 + bingData.getImages().get(0).getUrl());
                        }
                    }).start();
//                    MyThreadPool.threadPoolExecutor.execute(new Runnable() {
//                        @Override
//                        public void run() {
//
//                        }
//                    });
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, error -> {
            Log.i(TAG, error.getMessage());
        });
        MyVolleyRequestQueueSingleton.getInstance(context).getRequestQueue().add(request);
    }

}
